<template>
  <div>
    <el-form :inline="true" :model="dataForm" @keyup.enter="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.teamName" placeholder="代表队名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.realName" placeholder="选手姓名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.company" placeholder="单位" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dataForm.status" placeholder="状态" clearable>
          <el-option label="审核中" value="0"></el-option>
          <el-option label="报名成功" value="1"></el-option>
          <el-option label="完赛" value="201"></el-option>
          <el-option label="已确认晋级" value="202"></el-option>
          <el-option label="已取消/弃权" value="3"></el-option>
          <el-option label="比赛中" value="4"></el-option>
          <el-option label="已获晋级赛资格" value="501"></el-option>
          <el-option label="放弃晋级" value="502"></el-option>
          <el-option label="晋级成功" value="6"></el-option>
          <el-option label="弃权" value="7"></el-option>
          <el-option label="驳回" value="8"></el-option>
          <el-option label="待确认" value="9"></el-option>
          <el-option label="报名已截止" value="10"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地区" prop="province">
        <el-select style="width: 150px" placeholder="请选择" v-model="dataForm.province" @change="selectCity">
          <el-option value="" label="全国">全国</el-option>
          <el-option v-for="itemO in area.item" :key="itemO.code" :label="itemO.name" :value="itemO.code"> </el-option>
        </el-select>
        ~
        <el-select style="width: 150px" placeholder="请选择" v-model="dataForm.city">
          <el-option value="" label="全部">全部</el-option>
          <el-option v-for="itemO in areaCity.item" :key="itemO.code" :label="itemO.name" :value="itemO.code"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">{{ $t("query") }}</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="exportHandle()">导出模板表</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-if="hasPermission('sp:spmatchitemrecord:import') && isShowUploadFlag" @click="uploadCertificate()">导入模板表</el-button>
      </el-form-item>
      <el-form-item v-if="matchItem.item_name === '团体接力飞行赛' || matchItem.item_name === '蜂群舞蹈编程赛' ">
        <el-button @click="ranksSort()" size="primary">名次排序</el-button>
      </el-form-item>
      <el-form-item v-if="hasPermission('sp:spmatchitemrecord:cancleRanks')">
        <el-button @click="cancleAllScoreHandle()" size="primary">清除名次</el-button>
      </el-form-item>
      <el-form-item>
        <el-tag size="big">{{ matchItem ? matchItem.match_name : "" }}</el-tag>
        <el-tag size="big" style="margin-left: 10px">{{ matchItem ? matchItem.item_name : "" }}</el-tag>
        <el-tag size="big" style="margin-left: 10px">{{ dataForm.groupNameFile ? dataForm.groupNameFile : "" }}</el-tag>
      </el-form-item>
    </el-form>

    <el-table v-loading="dataListLoading" :data="dataList" border @selection-change="dataListSelectionChangeHandle" @sort-change="dataListSortChangeHandle" style="width: 100%">
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="id" width="80" label="序号" sortable="custom" header-align="center" align="center"></el-table-column>
      <el-table-column prop="sort" sortable="custom" width="120" label="抽签结果" header-align="center" align="center"></el-table-column>
      <el-table-column prop="teamName" width="250" label="代表队名称" header-align="center" align="center">
        <template v-slot="scope">
          <el-button type="text" @click="detailHandle(scope.row.teamId)">{{ scope.row.teamName }}</el-button>
        </template>
      </el-table-column>
      <!-- 点击代表队名称，弹出主领队信息（代表队名称-代表队单位-主领队）：姓名、性别、所属单位、电话、照片
      <el-table-column prop="company" width="250" label="代表队单位" header-align="center" align="center"></el-table-column>
      -->
      <el-table-column prop="groupName" width="250" label="队伍名称" header-align="center" align="center">
        <template v-slot="scope">
          <el-button type="text" @click="groupHandle(scope.row)">{{ scope.row.groupName }}</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="realName" width="200" label="选手" header-align="center" align="center">
        <template v-slot="scope">
          <!--按照顿号分割字符串-->
          <block v-for="(item, index) in (scope.row.userId || '').split('、')" :key="index">
            <el-button type="text" @click="userHandle(item)">{{ index != 0 ? "、" : "" }}{{ (scope.row.realName || "").split("、")[index] }}</el-button>
          </block>
        </template>
      </el-table-column>
      <el-table-column prop="ticket" width="350" label="选手编号" header-align="center" align="center"></el-table-column>
      <el-table-column prop="teacher" width="150" label="指导老师" header-align="center" align="center"></el-table-column>
      <el-table-column prop="score" v-if="scores[0]" width="100" :label="$t(scores[0])" header-align="center" align="center"></el-table-column>
      <el-table-column prop="score1" v-if="scores[1]" width="100" :label="$t(scores[1])" header-align="center" align="center"></el-table-column>
      <el-table-column prop="score2" v-if="scores[2]" width="100" :label="$t(scores[2])" header-align="center" align="center"></el-table-column>
      <el-table-column prop="ranks" width="100" label="名次" sortable="custom" header-align="center" align="center"></el-table-column>
      <el-table-column prop="grade" width="100" label="奖等" header-align="center" align="center"></el-table-column>
      <el-table-column prop="status" width="120" label="状态" header-align="center" align="center">
        <template v-slot="scope">
          <el-tag>{{ statusTranslate(scope.row.status, scope.row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" width="100" label="备注" header-align="center" align="center"></el-table-column>
      <el-table-column :label="$t('handle')" fixed="right" header-align="center" align="center" width="150" v-if="hasPermission('sp:spmatchitemrecord:opra')">
        <template v-slot="scope">
          <el-button type="text" size="small" v-if="riseCondition(scope.row.status, scope.row) && hasPermission('sp:spmatchitemrecord:rise')" @click="riseHandle(scope.row.id)">推荐晋级</el-button>
          <el-button type="text" size="small" v-if="((scope.row.status === 2 && scope.row.isRise === 1) || (scope.row.status === 5 && scope.row.rejectReason === '放弃晋级')) && hasPermission('sp:spmatchitemrecord:cancleRise')" @click="cancleRiseHandle(scope.row.id)">重置完赛</el-button>
          <el-button type="text" size="small" v-if="(scope.row.status === 1 || scope.row.status === 2 || (scope.row.status===5 && scope.row.rejectReason=='放弃晋级')) && hasPermission('sp:spmatchitemrecord:cancleScore')" @click="cancleScoreHandle(scope.row.id)">清除成绩</el-button>
          <el-button type="text" size="small" v-if="scope.row.status === 1 && hasPermission('sp:spmatchitemrecord:cancle')" @click="cancleHandle(scope.row.id)">弃权</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination :current-page="page" :page-sizes="[10, 20, 50, 100]" :page-size="limit" :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="pageSizeChangeHandle" @current-change="pageCurrentChangeHandle"> </el-pagination>
    <upload v-if="uploadVisible3" ref="upload3" :uploadurl="'/sp/spmatchitemteam/importMatchScore?matchItemId=' + dataForm.matchItemId" downloadurl="/sp/spmatchitemteam/exportMatchScoreError" @refreshDataList="getDataList"></upload>

    <!--修改成绩弹窗-->
    <el-dialog v-model="scoreDialogVisible" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="scoreDataForm" label-width="120px">
        <el-form-item prop="score" label="维度一">
          <el-input v-model="scoreDataForm.score"></el-input>
        </el-form-item>
        <el-form-item prop="score1" label="维度二">
          <el-input v-model="scoreDataForm.score1"></el-input>
        </el-form-item>
        <el-form-item prop="score2" label="维度三">
          <el-input v-model="scoreDataForm.score2"></el-input>
        </el-form-item>
        <el-form-item prop="ranks" label="名次">
          <el-input v-model="scoreDataForm.ranks"></el-input>
        </el-form-item>
        <el-form-item prop="grade" label="奖等">
          <el-input v-model="scoreDataForm.grade"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="scoreDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="updScoreHandle()">确认修改</el-button>
      </template>
    </el-dialog>

    <!-- 弹窗, 发送短信 -->
    <groupDetail v-if="groupVisible" ref="send" @refreshDataList="getDataList"></groupDetail>
    <!-- 弹窗, 选手 -->
    <userDetail v-if="userVisible" ref="userRef" @refreshDataList="getDataList"></userDetail>
    <!-- 弹窗, 代表队 -->
    <TeamDetail v-if="detailVisible" ref="teamRef" @refreshDataList="getDataList"></TeamDetail>
  </div>
</template>
<script lang="ts">
import useView from "@/hooks/useView";
import { defineComponent, reactive, toRefs } from "vue";
import baseService from "@/service/baseService";
import TeamDetail from "@/views/sp/spteam-detail.vue";
import UserDetail from "@/views/sp/spuser-detail.vue";
import GroupDetail from "@/views/sp/spmatchitemteam-detail.vue";
import Upload from "@/views/sp/score-upload.vue";
import app from "@/constants/app";
import qs from "qs";
import { getToken } from "@/utils/cache";
import { IObject } from "@/types/interface";
export default defineComponent({
  components: {
    Upload,
    TeamDetail,
    UserDetail,
    GroupDetail
  },
  name: "RenRecordTeam",
  setup() {
    const state = reactive({
      uploadVisible3: false,
      scoreDialogVisible: false,
      getDataListURL: "/sp/spmatchitemteam/signRecordTeam",
      createdIsNeed: false,
      activatedIsNeed: false,
      getDataListIsPage: true,
      userVisible: false,
      exportURL: "/sp/spmatchitemteam/signRecordExport",
      deleteURL: "/sp/spmatchitemteam",
      deleteIsBatch: true,
      dataForm: {
        matchName: "",
        item: "",
        matchItemId: "",
        teamId: "",
        teamName: "",
        isRise: "",
        status: "",
        company: "",
        realName: "",
        groupId: "",
        groupNameFile: "",
        province: "",
        city: "",
        fileName: ""
      },
      matchItem: {
        match_name: "",
        item_name: "",
        match_level: "" as any
      },
      scoreDataForm: {
        id: "",
        score: "",
        score1: "",
        score2: "",
        ranks: "",
        grade: ""
      },
      groupVisible: false,
      detailVisible: false,
      scores: [],
      activeName: "first",
      area: { code: "0", item: [{ code: "0", name: "请选择" }] },
      areaCity: { code: "0", item: [{ code: "0", name: "请选择" }] },
      isShowUploadFlag: true
    });
    return { ...useView(state), ...toRefs(state) };
  },
  watch: {},
  created() {
    this.areaList(this.area);
  },
  mounted() {
    //获取上个页面传来的参数
    this.dataForm.matchItemId = this.$route.query.matchItemId + "";
    this.dataForm.groupId = this.$route.query.id + "";
    this.dataForm.groupNameFile = this.$route.query.groupName + "";

    this.queryBymatchItemId(this.dataForm.matchItemId);
    this.query();
  },
  methods: {
    // 调用后台方法rise，晋级当前参赛小组
    riseHandle(id?: string) {
      this.$confirm("确认晋级？", this.$t("prompt.title"), {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning"
      }).then(() => {
        baseService.post("/sp/spmatchitemteam/rise", { id: id, status: "1" }).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.query();
          }
        });
      });
    },
    // 弃权
    cancleHandle(id?: string) {
      this.$confirm("确认弃权？", "弃权", {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning"
      }).then(() => {
        baseService.post("/sp/spmatchitemteam/cancel", { id: id }).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.query();
          }
        });
      });
    },
    /**
     * 清除成绩
     * @param id
     */
    cancleScoreHandle(id?: string) {
      this.$confirm("确认清除成绩？", "清除成绩", {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning"
      }).then(() => {
        baseService.post("/sp/spmatchitemteam/cancleScore", { id: id }).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.query();
          }
        });
      });
    },

    /**
     * 清除名次
     * @param id  matchItemTeamId
     */
    cancleAllScoreHandle() {
      this.$confirm("确认清除成绩？", "清除成绩", {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning"
      }).then(() => {
        baseService.get("/sp/spmatchitemteam/clearAllScore", {type: '2', ...this.dataForm}).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.query();
          }
        });
      });
    },

    /**
     * 查询score配置
     * @param matchItemId
     */
    queryBymatchItemId(matchItemId: any) {
      baseService.post("/sp/spmatchitem/queryBymatchItemId", { id: matchItemId }).then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        } else {
          console.log(res.data);
          this.matchItem = res.data;
          this.dataForm.fileName = this.matchItem.item_name + "(" + this.dataForm.groupNameFile + ")";
          this.scores = res.data.scores.split(",");
          this.isShowUpload();
        }
      });
    },
    zhengshuHandle() {
      let ids: string[] = [];
      for (let i = 0; i < this.dataListSelections!.length; i++) {
        ids.push(this.dataListSelections![i].id);
      }
      window.location.href = `${app.api}/sp/spmatchitemteam/downloadFile?${qs.stringify({
        ...this.dataForm,
        token: getToken(),
        ids: ids.join(",")
      })}`;
    },
    // 获取省份
    areaList(target: any) {
      baseService.get("/front/fast/sys/areaDict/list?pid=" + target.code).then((e: any) => {
        target.item = e.data;
      });
    },
    // 选择城市
    selectCity() {
      if (this.dataForm.province) {
        this.areaCity.code = this.dataForm.province;
        this.areaList(this.areaCity);
      } else {
        this.dataForm.city = "";
        this.areaCity.item = [];
      }
    },
    uploadCertificate() {
      this.uploadVisible3 = true;
      this.$nextTick(() => {
        this.$refs.upload3.init();
      });
    },
    // 查看证书
    infoHandle(info: string) {
      window.open(info);
    },
    /**
     * 根据SpMatchItemTeamUser.id删除证书
     * @param id
     */
    updateHandle(id: number) {
      this.$confirm("确认删除证书？", "删除证书", {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning"
      }).then(() => {
        baseService.get("/sp/spmatchitemteam/delCertificate?id=" + id, {}).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.query();
          }
        });
      });
    },
    detailHandle(id?: string) {
      this.detailVisible = true;
      baseService.get("/sp/spteam/" + id).then((e: any) => {
        this.$nextTick(() => {
          if (e.data) {
            e.data.sex = e.data.sex == 0 ? "女" : "男";
          }
          this.$refs.teamRef.dataForm.row = e.data;
          this.$refs.teamRef.init();
        });
      });
    },
    //修改成绩
    updScoreHandle(id?: string) {
      baseService.get("/sp/spmatchitemteam/" + id).then((e: any) => {
        this.$nextTick(() => {
          this.scoreDataForm = e.data;
        });
        this.scoreDialogVisible = false;
      });
    },
    groupHandle(row: IObject) {
      this.groupVisible = true;
      this.$nextTick(() => {
        this.$refs.send.dataForm.row = row;
        this.$refs.send.init();
      });
    },
    userHandle(id?: string) {
      this.userVisible = true;
      baseService.get("/sp/spuser/" + id).then((e: any) => {
        this.$nextTick(() => {
          if (e.data) {
            e.data.sex = e.data.sex == 0 ? "女" : "男";
          }
          console.log(this.$refs.userRef.dataForm);
          this.$refs.userRef.dataForm.row = e.data;
          this.$refs.userRef.init();
        });
      });
    },

    /**
     * 重置完赛
     * @param id
     */
    cancleRiseHandle(id?: number) {
      this.$confirm("确认重置完赛？", this.$t("prompt.title"), {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning"
      }).then(() => {
        baseService.get("/sp/spmatchitemteam/cancleRise?id=" + id).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.query();
          }
        });
      });
    },
    /**
     * 名次排序
     */
    ranksSort() {
      const query = "?matchItemId=" + this.dataForm.matchItemId + "&groupId=" + this.dataForm.groupId;

      let action = 'ranksSortTeam';
      if(this.matchItem.item_name === '蜂群舞蹈编程赛'){
        action = 'ranksSortTeamFqwd';
      }


      baseService.get("/sp/spmatchitemteam/" + action + query).then((e: any) => {
        // 刷新数据
        this.query();
      });
    },

    //省级比赛统一控制不能上传成绩的功能开关按钮
    isShowUpload() {
      if (this.matchItem.match_level == 2) {
        baseService.get('/sys/params/sysParams').then(e => {
          let sysParams = e.data;
          if (sysParams.uploadProvinceScore == '1') {
            this.isShowUploadFlag = true
          } else {
            this.isShowUploadFlag = false
          }
        })
      }
    },

  }
});
</script>
